import {
  getPromotionProjectPage,
  sendPromotionProjectTemplateMessage,
  updatePromotionProjectState,
} from '@/services/api/api-promotion';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import { Modal, Tag, message } from 'antd';
import 'dayjs/locale/zh-cn';
import moment from 'moment';
import React, { useRef, useState } from 'react';
import { useAccess } from 'umi';
import AddPromotionProject from './AddPromotionProject';
import DetailsPromotionProject from './DetailsPromotionProject';

interface TablePromotionProjectProps { }

const TablePromotionProject: React.FC<TablePromotionProjectProps> = ({ }) => {
  const access = useAccess();

  const actionRef = useRef<ActionType>();

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [projectId, setProjectId] = useState('');

  const columns: ProColumns<PromotionData.Project>[] = [
    {
      title: '状态',
      dataIndex: 'run',
      copyable: true,
      ellipsis: true,
      width: '80px',
      valueType: 'select',
      valueEnum: {
        1: { text: '进行中' },
        2: { text: '已结束' },
        3: { text: '已暂停' },
      },
      render: (_, row) => {
        return (
          <Tag color={row.run === 1 ? 'green' : row.run === 2 ? 'red' : 'orange'}>
            {row.run === 1 ? '进行中' : row.run === 2 ? '已结束' : '已暂停'}
          </Tag>
        );
      },
    },
    {
      title: '标题',
      dataIndex: 'name',
      copyable: true,
      ellipsis: true,
      width: '30%',
      render: (_, row) => {
        return (
          <DetailsPromotionProject
            showType={'project'}
            project={row}
            onRefurbish={function (): void { }}
          />
        );
      },
    },
    {
      title: '任务类型',
      width: '20%',
      key: 'taskTypes',
      valueType: 'select',
      fieldProps: {
        mode: 'multiple',
        allowClear: true,
        showSearch: true,
        optionFilterProp: 'children',
        filterOption: (input: any, option: any) => {
          console.log(option);
          return option.label.includes(input);
        },
        options: [
          { value: '1', label: '公众号' },
          { value: '2', label: '视频号' },
          { value: '3', label: '抖音' },
        ],
      },
      render: (_, row) => {
        return (
          <div>
            {row.taskTypes.map((item) => (
              <Tag key={item} color={item === 1 ? '#1CAE1B' : item === 2 ? '#F5A34D' : '#060716'}>
                {item === 1 ? '公众号' : item === 2 ? '视频号' : '抖音'}
              </Tag>
            ))}
          </div>
        );
      },
    },
    {
      title: '指派',
      dataIndex: 'isAssign',
      width: '80px',
      valueType: 'select',
      valueEnum: {
        1: { text: '是' },
        0: { text: '否' },
      },
      render: (_, row) => {
        return (
          <Tag color={row.isAssign === 1 ? 'blue' : 'purple'}>
            {row.isAssign === 1 ? '是' : '否'}
          </Tag>
        );
      },
    },
    {
      title: '任务量',
      search: false,
      render: (_, row) => {
        return <span>{row.taskCount}</span>;
      },
    },
    {
      title: '截至日期',
      key: 'deadlines',
      dataIndex: 'deadline',
      valueType: 'dateRange',
      fieldProps: {
        allowClear: true,
        placeholder: ['开始日期', '结束日期'],
        format: 'YYYY-MM-DD',
        ranges: {
          今日: [moment(), moment()],
          本月: [moment().startOf('month'), moment().endOf('month')],
          上月: [
            moment().startOf('month').subtract(1, 'months'),
            moment().endOf('month').subtract(1, 'months'),
          ],
          最近7天: [moment().subtract(6, 'days'), moment()],
          最近60天: [moment().subtract(59, 'days'), moment()],
          最近90天: [moment().subtract(89, 'days'), moment()],
        },
      },
      render: (_, row) => {
        return <span>{row.deadline}</span>;
      },
    },
    {
      title: '创建时间',
      key: 'createdTimes',
      dataIndex: 'createdTime',
      valueType: 'dateRange',
      fieldProps: {
        allowClear: true,
        placeholder: ['开始日期', '结束日期'],
        format: 'YYYY-MM-DD',
        ranges: {
          今日: [moment(), moment()],
          本月: [moment().startOf('month'), moment().endOf('month')],
          上月: [
            moment().startOf('month').subtract(1, 'months'),
            moment().endOf('month').subtract(1, 'months'),
          ],
          最近7天: [moment().subtract(6, 'days'), moment()],
          最近60天: [moment().subtract(59, 'days'), moment()],
          最近90天: [moment().subtract(89, 'days'), moment()],
        },
      },
      render: (_, row) => {
        return <span>{row.createdTime}</span>;
      },
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (text, row, _, action) => [
        access.签到推广x更新 && (
          <a
            key="update_state"
            onClick={async () => {
              const response = await updatePromotionProjectState({ id: row.id });
              if (response.code === 0) {
                message.success('更新成功！');
                action?.reload();
              }
            }}
          >
            {row.state === 1 ? '关闭' : '开启'}
          </a>
        ),
        access.签到推广x更新 && <a
          key="send_template_message"
          onClick={async () => {
            setProjectId(row.id);
            setIsModalOpen(true);
          }}
        >
          推送
        </a>
      ],
    },
  ];

  /**
   * 请求网络
   * @param value
   */
  const request = async (params = {}) => {
    const response = await getPromotionProjectPage({ ...params });
    return Promise.resolve({
      data: response.data.data,
      total: response.data.total,
      success: response.code === 0,
    });
  };


  return (
    <PageContainer
      extra={[
        access.签到推广x创建 && (
          <AddPromotionProject
            key={'add_promotion_project'}
            onRefurbish={(id) => {
              actionRef?.current?.reset();
              setProjectId(id);
              setIsModalOpen(true);
            }}
          />
        ),
      ]}
    >
      <Modal
        title="是否要全局推送？"
        open={isModalOpen}
        onOk={async () => {
          const pushResponse = await sendPromotionProjectTemplateMessage({
            id: projectId,
          });
          if (pushResponse.code == 0) {
            message.success('推送成功');
            setIsModalOpen(false);
          }
        }}
        onCancel={() => {
          setIsModalOpen(false);
        }}
      >
        <p>对所选用户进行微信服务号模板消息推送。</p>
      </Modal>

      <ProTable<PromotionData.Project>
        columns={columns}
        actionRef={actionRef}
        cardBordered
        rowKey="id"
        tableLayout="fixed"
        dateFormatter="string"
        request={request}
        pagination={{
          showQuickJumper: true,
          showSizeChanger: true,
          defaultPageSize: 20,
        }}
        toolBarRender={() => []}
      />
    </PageContainer>
  );
};
export default TablePromotionProject;
